require 'fileutils'

def ask(question)
  answer = ""
  loop do
    puts "\n#{question}"
    answer = gets.chomp.to_s

    break if !File.directory? "component/#{answer}"

    puts "\033[31m\n-------------------------该模块名已存在请重新输入.---------------------------\n\033[0m\n" 
  end
  answer
end

def replace_variables_in_third(pod_name)
  file_names = ['template/Pod/ModuleManager/PROJECTManager.h', 'template/Pod/ModuleManager/PROJECTManager.m']
  file_names.each do |file_name|
    text = File.read(file_name)
    text.gsub!("PROJECT", pod_name)
    File.open(file_name, "w") { |file| file.puts text }
  end
end

def replace_variables_in_podspec(pod_name)
  file_names = ['template/NAME.podspec']
  file_names.each do |file_name|
    text = File.read(file_name)
    text.gsub!("${POD_NAME}", pod_name)
    File.open(file_name, "w") { |file| file.puts text }
  end
end

def rename_template_files(pod_name)
  FileUtils.mv "template/Pod/ModuleManager/PROJECTManager.h", "template/Pod/ModuleManager/#{pod_name}Manager.h"
  FileUtils.mv "template/Pod/ModuleManager/PROJECTManager.m", "template/Pod/ModuleManager/#{pod_name}Manager.m"
  FileUtils.mv "template/NAME.podspec", "template/#{pod_name}.podspec"
end

def rename_classes_folder(pod_name)
  FileUtils.mv "template/Pod", "template/#{pod_name}"
end

def reinitialize_git_repo
  `rm -rf template/.git`
  `rm -rf template/template.rb`
end

def move_pod(pod_name)
  `mkdir ./component/#{pod_name}`
  `mv template/* ./component/#{pod_name}`
end

def delete_template
  `rm -rf template`
end

def write_pod_in_podfile(pod_name)
  file_names = ['Podfile']
  file_names.each do |file_name|
    text = File.read(file_name)
    text.gsub!("#功能模块", "pod '#{pod_name}', :path => 'component/#{pod_name}'\n        #功能模块")
    File.open(file_name, "w") { |file| file.puts text }
  end
end

def pod_install
  `IS_SOURCE=1 pod install`
  puts "\033[34m-------------------------创建完毕---------------------------\033[0m\n"
end



input = ask("-------------------------请输入要创建的模块名字---------------------------")

replace_variables_in_third(input)
replace_variables_in_podspec(input)
rename_template_files(input)
rename_classes_folder(input)
reinitialize_git_repo
move_pod(input)
delete_template
write_pod_in_podfile(input)
pod_install
